package com.none.staff.net;

import android.text.TextUtils;

import com.none.staff.model.ConfigBean;
import com.none.staff.net.interfaces.DownloadFileListener;
import com.none.staff.utils.Constants;
import com.none.staff.utils.FileUtils;
import com.peter.baselibrary.utils.LogUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {

    private static RetrofitUtil retrofitUtil;
    private static RedApiServer redApiServer;

    private RetrofitUtil() {
        redApiServer = createApiServer();
    }

    public static RetrofitUtil getInstances() {
        synchronized (RetrofitUtil.class) {
            if (retrofitUtil == null) {
                retrofitUtil = new RetrofitUtil();
            }
            return retrofitUtil;
        }
    }

    private RedApiServer createApiServer() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(RedApiServer.class);
    }

    /**
     * get config file content
     *
     * @param configUrl
     * @param callback
     */
    public void getConfig(String configUrl, Callback<ConfigBean> callback) {
        Call<ConfigBean> call = redApiServer.getConfig(configUrl);
        call.enqueue(callback);
    }

    public synchronized void downloadWebResource(String resourceUrl, DownloadFileListener resourcesListener) {
        String resourceName = null;
        if (FileUtils.createOrExistsDir(Constants.getDownloadResourcesFilePath())) {
            int last = resourceUrl.lastIndexOf("/");
            if (last != -1) {
                resourceName = resourceUrl.substring(last);
            }
        }
        String resourcePath = Constants.getDownloadResourcesFilePath()  + resourceName;
        File resourceFile = new File(resourcePath);
        resourcesListener.onStart();
        Call<ResponseBody> resourceCall = redApiServer.downloadClientPackage(resourceUrl);
        resourceCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                //下载文件放在子线程
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        //保存到本地
                        writeFile2Disk(response, resourcePath, resourceFile, resourcesListener);
                    }
                }.start();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                resourcesListener.onFailure(t.getMessage());
            }
        });

    }


    /**
     * @param url
     */
    public void downLoadApkFile(String url, DownloadFileListener loadApkFileListener) {
        String name = url;
        String apkPath = null;
        String PATH_CHALLENGE_VIDEO = Constants.getDownloadApkFilePath();
        //通过Url得到文件并创建本地文件
        if (FileUtils.createOrExistsDir(PATH_CHALLENGE_VIDEO)) {
            int i = name.lastIndexOf('/');//一定是找最后一个'/'出现的位置
            if (i != -1) {
                name = name.substring(i);
                apkPath = PATH_CHALLENGE_VIDEO +
                        name;
            }
        }
        if (TextUtils.isEmpty(apkPath)) {
            LogUtils.INSTANCE.e("downloadResource: 存储路径为空了");
            return;
        }
        //建立一个文件
        File mFile = new File(apkPath);
        if (!FileUtils.isFileExists(mFile) && FileUtils.createOrExistsFile(mFile)) {
            Call<ResponseBody> call = redApiServer.downLoadApkFile(url);
            loadApkFileListener.onStart();
            String finalApkPath = apkPath;
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    //下载文件放在子线程
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            //保存到本地
                            writeFile2Disk(response, finalApkPath, mFile, loadApkFileListener);
                        }
                    }.start();

                    LogUtils.INSTANCE.e(response.message());
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    loadApkFileListener.onFailure(t.getMessage());
                    LogUtils.INSTANCE.e(t.getMessage());
                }
            });
        } else {
            loadApkFileListener.onFinish(apkPath);
        }

    }

    //将下载的文件写入本地存储
    private void writeFile2Disk(Response<ResponseBody> response, String apkPath, File file, DownloadFileListener downloadListener) {
        downloadListener.onStart();
        long currentLength = 0;
        OutputStream os = null;

        InputStream is = response.body().byteStream(); //获取下载输入流
        long totalLength = response.body().contentLength();

        try {
            os = new FileOutputStream(file); //输出流
            int len;
            byte[] buff = new byte[1024];
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
                currentLength += len;
//                LogUtils.INSTANCE.e("当前进度: " + currentLength);
                //计算当前下载百分比，并经由回调传出
                downloadListener.onProgress((int) (100 * currentLength / totalLength));
                //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径
                if ((int) (100 * currentLength / totalLength) == 100) {
                    downloadListener.onFinish(apkPath); //下载完成
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close(); //关闭输出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close(); //关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
